<?php

include 'inc/conn.php';

function generatePackageList($imgid, $packid) {
    $result = "<select name=\"packageid$imgid\" id=\"packageid$imgid\" onchange=\"updatePackageId('$imgid')\">";

    $res = mysql_query("select id,title from ats_package");
    while ($pcg = mysql_fetch_array($res)) {
        if ($pcg[0] == $packid) {
            $selected = 'selected';
        } else {
            $selected = '';
        }

        $result .= "<option $selected value='$pcg[0]'>$pcg[1]</option>";
    }

    $result .= "</select>";
    return $result;
}

$id = '0';
$mode = 'a';
$packageid = 0;
$filename = '';
if (isset($_POST['id']))
    $id = $_POST['id'];

if (isset($_POST['mode']))
    $mode = $_POST['mode'];

if (isset($_POST['packageid']))
    $packageid = $_POST['packageid'];

if (isset($_POST['filename']))
    $filename = $_POST['filename'];

$tablename = "ats_frontimages";
switch ($mode) {
    case 'a':
        //add, insert new image
        $sql = "insert into $tablename(filename, packageid, active) values('$filename','1',1)";

        $rs = mysql_query($sql)
                or die('sql error');
        $newid = mysql_insert_id();

        $rowid = "row$newid";
        $newstring = "<tr id='$rowid'><td width='50%'><img width='100' src='$filename' /></td><td>".  generatePackageList($newid, $packageid)."</td><td><a href='#' onclick=\"deleteHomeImg('$newid')\">Delete</a></td></tr>";

        //echo $newid;
        echo $newstring;
        break;
    case 'd':
        //delete image
        $sql = "select * from $tablename where id=$id";

        $res = mysql_query($sql);
        $row = mysql_fetch_row($res);
        if (file_exists($row[1]))
            unlink($row[1]);

        $sql = "delete from $tablename where id=$id";
        $rs = mysql_query($sql);
        echo $sql;
        break;
}
?>
